/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { notification } from 'antd';
import { stringify } from 'querystring';
import { history } from 'umi';
import { message } from 'antd';



const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};
/**
 * 异常处理程序
 */

const errorHandler = (error) => {
  const { response } = error;
  console.log('errorHandler', error)
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  }
  return response;
};
/**
 * 配置request请求时的默认参数
 */
const { REACT_APP_ENV } = process.env;

// export const EXCELLENTPM_API = 'http://47.97.111.187'
// export const EXCELLENTPM_API = 'http://localhost:8101'

const getApiHost = () => {
  // console.log(REACT_APP_ENV, window.location)
  return "http://115.29.189.233:8102"
  // return window.location.protocol + "//" + window.location.hostname + ":8102";
}

export const EXCELLENTPM_API = getApiHost();
const getAccessToken = () => {
  return `${localStorage.getItem('access-token')}`;
}

const getEid = () => {
  return `${localStorage.getItem('e_id')}`;
}



function createClient(baseUrl) {
  const request = extend({
    prefix: baseUrl,
    mode: 'cors',
    // 默认错误处理
    errorHandler,
    credentials: 'include', // 默认请求是否带上cookie
  });
  return request;
}

const defaultRequest = createClient(EXCELLENTPM_API);

// response拦截器, 处理response
defaultRequest.interceptors.response.use(async response => {
  let contentType = response.headers.get("Content-Type")
  if (contentType === "application/json") {
    const data = await response.clone().json();

    if (data && (data.code === 4001 || data.code === 4002)) {
      let redirect = window.location.href;
      console.log(redirect);
      if (redirect.indexOf('/user/login') > 0) {
        return {};
      }
      const queryString = stringify({
        redirect: window.location.href,
      });
      history.push(`/user/login?${queryString}`);
      return {};
    }
    if (data && (data.code === 10001000)) {
      history.push(`/user/login`);
      return {};  
    }
    if (!data.code) {
      message.error(response.url)
    }
    if (data && (data.code !== 200) && data.errMsg) {
      message.error(data.errMsg)
    }
  } else {
    return {}
  }
  return response;
});

// response拦截器, 处理response
defaultRequest.interceptors.request.use((url, options) => {
  let params = {}
  if (options.params) {
    params = { ...options.params }
    let paramKeys = Object.keys(options.params);
    for (let index in paramKeys) {
      let pv = options.params[paramKeys[index]];
      if (typeof (pv) === 'string' && pv.trim() === "") {
        delete params[paramKeys[index]];
      }
    }
  }
  const headers = {};
  headers.AccessToken = getAccessToken();
  let eid = getEid();
  if (eid) {
    headers.e_id = eid;
  }
  return {
    options: {
      ...options,
      params: params,
      headers: headers
    },
  };
});

export const mockRequest = extend();
export const host = EXCELLENTPM_API;
export const normalRequest = extend();
export default defaultRequest;


